package org.pearl.springbootsecurity.demo.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import org.pearl.springbootsecurity.demo.MP.data.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by TD on 2021/9/3
 */
@Configuration
@EnableConfigurationProperties(PearlDataScopeProperties.class)
public class MybatisPlusConfig {

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(PearlDataScopeProperties pearlDataScopeProperties,PearlDataScopeHandler dataScopeHandler) {
        // 添加租户插件
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false ,3.4已移除
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor();
        TenantLineHandler myTenantLineHandler = new MyTenantLineHandler();
        tenantLineInnerInterceptor.setTenantLineHandler(myTenantLineHandler);
        //interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
        if (pearlDataScopeProperties.getEnabled()) {
            // 开启配置，添加数据权限插件
            interceptor.addInnerInterceptor(new DataScopeInterceptor(dataScopeHandler));
        }
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }

    /**
     * 数据权限处理器
     *
     * @return
     */
    @Bean
    public PearlDataScopeHandler dataScopeHandler(PearlDataScopeProperties pearlDataScopeProperties) {
        return new PearlDataScopeHandler(pearlDataScopeProperties);
    }


}
